package com.labot.dao.hibernate;

import java.util.HashSet;
import java.util.List;





import java.util.Set;

import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.labot.dao.AreaDao;
import com.labot.model.Area;


/**
 * This class interacts with Hibernate session to save/delete and
 * retrieve User objects.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *   Modified by <a href="mailto:dan@getrolling.com">Dan Kibler</a>
 *   Extended to implement Acegi UserDetailsService interface by David Carter david@carter.net
 *   Modified by <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> to work with
 *   the new BaseDaoHibernate implementation that uses generics.
 *   Modified by jgarcia (updated to hibernate 4)
*/
@Repository("areaDao")
public class AreaDaoHibernate extends HistoryTackerDaoHibernate<Area, Long> implements AreaDao {

    /**
     * Constructor that sets the entity to User.class.
     */
    public AreaDaoHibernate() {
        super(Area.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public Set<Area> getAreas() {
        Query qry = getSession().createQuery("from Area c WHERE deletiontime is null order by upper(c.nombre)");
        Set<Area> areas = new HashSet<Area>(qry.list());
        return areas;
    }

    /**
     * {@inheritDoc}
     */
    public Area saveArea(Area area) {
        if (log.isDebugEnabled()) {
            log.debug("user's id: " + area.getNombre());
        }
        super.save(area);
        getSession().flush();
        return area;
    }

    /**
     * Overridden simply to call the saveUser method. This is happening
     * because saveUser flushes the session and saveObject of BaseDaoHibernate
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public Area save(Area area) {
        return this.saveArea(area);
    }

    /**
     * {@inheritDoc}
     * @throws Exception 
    */

	@SuppressWarnings("unchecked")
	@Override
	public Area buscarAreaPorNombre(String nombre) throws Exception {
		List<Area> areas = getSession().createCriteria(Area.class).add(Restrictions.eq("nombre", nombre)).list();
        if (areas == null || areas.isEmpty()) {
            throw new Exception("area:  '" + nombre + "' not found...");
        } else {
            return (Area)areas.get(0); 
        }
	}

	@Override
	public Area buscarArea(Long id) {
		 Query qry = getSession().createQuery("from Area a WHERE a.id = :id");
		 qry.setParameter("id", id);
		 return (Area)  qry.list().get(0);
	}

    /**
     * {@inheritDoc}
    */
}
